package org.trackcore.utils;

import java.util.Map;

import java.util.Collections;
import java.util.List;
import java.util.Map;

public class DataUtils {
    /**
     * 获取List
     * @param map
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List<Map<String, Object>> getList(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value instanceof List) {
            return (List<Map<String, Object>>) value;
        }
        return Collections.emptyList(); // 返回空List而不是null
    }

    /**
     * 获取String
     * @param map
     * @param key
     * @return
     */
    public static String getString(Map<String, Object> map, String key) {
        return map.containsKey(key) ? String.valueOf(map.get(key)) : null;
    }

    /**
     * 获取String
     * @param map
     * @param key
     * @param defaultValue
     * @return
     */
    public static String getString(Map<String, Object> map, String key, String defaultValue) {
        return map.containsKey(key) ? String.valueOf(map.get(key)) : defaultValue;
    }

    /**
     * 获取HandlerKey
     * @param item
     * @return
     */
    public static String getHandlerKey(Map<String, Object> item) {
        return getString(item, "type", "") + "_" + getString(item, "subType", "");
    }

    /**
     * 获取Double
     * @param map
     * @param key
     * @return
     */
    public static Double getDouble(Map<String, Object> map, String key) {
        try {
            return map.containsKey(key) ? Double.parseDouble(String.valueOf(map.get(key))) : null;
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 获取Long
     * @param map
     * @param key
     * @return
     */
    public static Long getLong(Map<String, Object> map, String key) {
        try {
            return map.containsKey(key) ? Long.parseLong(String.valueOf(map.get(key))) : null;
        } catch (NumberFormatException e) {
            return null;
        }
    }

    public static int getInt(Map<String, Object> map, String key, int defaultValue) {
        Integer result = getInt(map, key);
        return result != null ? result : defaultValue;
    }

    public static Integer getInt(Map<String, Object> map, String key) {
        if (map == null || !map.containsKey(key)) {
            return null;
        }

        Object value = map.get(key);
        if (value instanceof Integer) {
            return (Integer) value;
        }

        try {
            if (value instanceof Number) {
                return ((Number) value).intValue();
            }
            return Integer.parseInt(String.valueOf(value));
        } catch (NumberFormatException e) {
            return null;
        }
    }

    public static Boolean getBoolean(Map<String, Object> data, String success) {
        return data.containsKey(success) ? Boolean.valueOf(String.valueOf(data.get(success))) : null;
    }
}

